<?php
/**
 * Created by PhpStorm.
 * User: iyahe@qq.com (天明)
 * Date: 2017/12/18
 * Time: 11:17
 */
namespace app\api\model;
use app\api\controller\Kefu;
use GatewayClient\Gateway;
use think\Cache;
use think\Db;
use think\Model;

class SocketModel extends Model{
    private static $_instance;
    public static function make() {
        if (!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    public function online($data,$client_id){
        $uid = $data['data']['uid'];
        $status = $data['code'];
        Gateway::$registerAddress = '127.0.0.1:4005';
        UserModel::make()->onlineSet($uid,$status);
        if($status){
            Cache::set($client_id,$uid);//保存$client_id信息
            Gateway::bindUid($client_id,$uid);
        }else{
            Gateway::unbindUid($client_id,$uid);
        }
        setlogs($client_id,$uid.'绑定状态'.$status);
        //Gateway::sendToClient($client_id,self::socketData('绑定成功'));
    }
    public function onClose($data,$client_id){
        setlogs($data,$client_id.'onClose');
    }
    public function chat($data,$client_id){
        $uuid = $data['data']['uuid'];
        $content = $data['data']['content'];
        $firstChat = $data['data']['firstChat'];
        $myuid = $data['uid'];
        Gateway::$registerAddress = '127.0.0.1:4005';
        ChatlogModel::make()->addlog($content,$myuid,$uuid);
        if($firstChat && false){
            $kefu = new Kefu();
            $openid = UserModel::make()->getUserInfo($uuid,'user_openid');
            $kefuData = [];
            $kefuData['title'] = 'Hi,有人给你发消息啦，快来看看!';
            $kefuData['pagepath'] = 'pages/chat/index?uid='.$myuid;
            $kefuData['thumb_media_id'] = 'XBnt0DDsCV3lMyjqgzH576JiIvGn8FKvZUwPti9manQclcAsP51Ka8DYfcopukRV';
            setlogs($kefuData,'$kefuData');
            Gateway::sendToClient($client_id,self::socketData('请稍等,小丸子已经把通知推送给小伙伴了,小伙伴马上就到...','chat',[
                'header'=>'https://play.he29.com/public/img/logo.jpg',
                'uuid'=>$uuid
            ],300));
            return $kefu->sendKefuMessage($openid['user_openid'],$kefuData,'mini');
        }
        Gateway::sendToUid($uuid,self::socketData($content,'chat',['uuid'=>$uuid]));
    }
    public static function socketData($msg='',$action='action',$data='',$code=200){
        $returnData =  json_encode([
            'code'=>$code,
            'info'=>$data,
            'msg'=>$msg,
            'type'=>$action
        ],JSON_UNESCAPED_UNICODE);
        setlogs(888,'$returnData222');
        setlogs($returnData,'$returnData');
        return $returnData;
    }
}